﻿using PoundConsole.IdCard;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PoundConsole
{
    internal class Program
    {
        private static SerialPort _serialPort1;
        private static SerialPort _serialPort2;
        private static SerialPort _serialPort3;
        static Queue<double> _readings1 = new Queue<double>(); // 数据队列
        static StableWeightDetector swd1 = new StableWeightDetector(_readings1);
        static Queue<double> _readings2 = new Queue<double>(); // 数据队列
        static StableWeightDetector swd2 = new StableWeightDetector(_readings2);
        static Queue<double> _readings3 = new Queue<double>(); // 数据队列
        static StableWeightDetector swd3 = new StableWeightDetector(_readings3);
        //地磅身份证
        public static string idCardNo1;
        public static string idCardNo2;
        public static string idCardNo3;

        static void Main(string[] args)
        {
            string SerialPort1 = ConfigurationManager.AppSettings["SerialPort1"];
            string SerialPort2 = ConfigurationManager.AppSettings["SerialPort2"];
            string SerialPort3 = ConfigurationManager.AppSettings["SerialPort3"];
            Console.WriteLine($"正在监听地磅数据，按任意键退出...");
            Task.Run(async () =>
            {
                _serialPort1 = new SerialPort(SerialPort1, 9600);
                if (_serialPort1.IsOpen)
                {
                    _serialPort1.Close();
                }
                _serialPort1.Open();

                if (_serialPort1.IsOpen)
                {
                    _serialPort1.DataReceived += _serialPort1_DataReceived;
                    await Task.Delay(200);
                }
            });
            Task.Run(async () =>
            {
                _serialPort2 = new SerialPort(SerialPort2, 9600);
                if (_serialPort2.IsOpen)
                {
                    _serialPort2.Close();
                }
                _serialPort2.Open();
                if (_serialPort2.IsOpen)
                {
                    //int bytesToRead = _serialPort2.BytesToRead;
                    //byte[] buffer = new byte[bytesToRead];
                    //_serialPort2.Read(buffer, 0, bytesToRead);
                    //// 解析接收到的数据
                    //decimal weight = ParseScaleData(buffer, SerialPort2);
                    ////Console.WriteLine($"{DateTime.Now}解析到{SerialPort2}重量: {weight} 吨");        
                    _serialPort2.DataReceived += _serialPort2_DataReceived; ;
                    await Task.Delay(200);
                }
            });
            Task.Run(async () =>
            {
                _serialPort3 = new SerialPort(SerialPort3, 9600);
                if (_serialPort3.IsOpen)
                {
                    _serialPort3.Close();
                }
                _serialPort3.Open();

                if (_serialPort3.IsOpen)
                {                   
                    _serialPort3.DataReceived += _serialPort3_DataReceived;
                    await Task.Delay(200);
                }
            });
            Console.WriteLine($"正在监听身份证读卡器...");
            Task.Run(() =>
            {
                //1号地磅身份证读卡器
                IdCardHelper idCardHelper1 = new IdCardHelper();
                while (true)
                {
                     byte[] idBytes = idCardHelper1.senddata("192.168.10.163", 23);
                    try
                    {
                        idCardNo1 = idCardHelper1.jiexie(idBytes);
                    }
                    catch (Exception)
                    {
                    }
                   
                    LogHelper.WriteLog($"{DateTime.Now}读取到地磅1身份证：{idCardNo1}");

                    Task.Delay(1000);  //此处间隔过段会导致身份证读卡器响应异常
                }
            });
            //Task.Run(() =>
            //{
            //    while (true)
            //    {
            //        //2号地磅身份证读卡器
            //        byte[] idBytes = IdCardHelper.senddata("192.168.10.164", 23);
            //        idCardNo2 = IdCardHelper.jiexie(idBytes);
            //        Task.Delay(1000);
            //    }
            //});
            Task.Run(() =>
            {
                //3号地磅身份证读卡器
                IdCardHelper idCardHelper3 = new IdCardHelper();
                while (true)
                {                   
                    byte[] idBytes = idCardHelper3.senddata("192.168.10.165", 23);
                    try
                    {
                        idCardNo3 = idCardHelper3.jiexie(idBytes);
                    }
                    catch (Exception)
                    {
                    }

                    Task.Delay(1000);
                }
            });
            Console.ReadLine();
            SerialPortClose();
        }

        private static void _serialPort3_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytesToRead = _serialPort3.BytesToRead;
            byte[] buffer = new byte[bytesToRead];
            _serialPort3.Read(buffer, 0, bytesToRead);
            //3号地磅每次收到2次数据，过滤长度为4的数据
            if (buffer.Length >= 8)
            {
                double weight = ParseScaleData(buffer, _serialPort3.PortName);
                swd3.OutputResult(weight, _readings3, _serialPort3.PortName);
            }


        }

        private static void _serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytesToRead = _serialPort2.BytesToRead;
            byte[] buffer = new byte[bytesToRead];
            _serialPort2.Read(buffer, 0, bytesToRead);
            double weight = ParseScaleData(buffer, _serialPort2.PortName);
            swd2.OutputResult(weight, _readings2, _serialPort2.PortName);

        }

        private static void _serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytesToRead = _serialPort1.BytesToRead;
            byte[] buffer = new byte[bytesToRead];
            _serialPort1.Read(buffer, 0, bytesToRead);
            double weight = ParseScaleData(buffer, _serialPort1.PortName);
            swd1.OutputResult(weight, _readings1, _serialPort1.PortName);
        }

        private static void SerialPortClose()
        {
            if (_serialPort1.IsOpen)
            {
                _serialPort1.Close();
            }
            if (_serialPort2.IsOpen)
            {
                _serialPort2.Close();
            }
            if (_serialPort3.IsOpen)
            {
                _serialPort3.Close();
            }
        }
        private static double ParseScaleData(byte[] data, string serialPort)
        {

            // 将16进制数据转换为ASCII字符串
            string asciiString = Encoding.ASCII.GetString(data);
            string weightStr = data.ToString();
            if (serialPort == "COM1" || serialPort == "COM2")
            {
                //1,2号磅
                // 检查数据格式是否正确（示例格式：000.000=）
                if (asciiString.Length >= 7 && asciiString.Contains(".") && asciiString.EndsWith("="))
                {
                    // 提取重量部分（去掉最后的等号）
                    weightStr = asciiString.Substring(0, asciiString.Length - 1);
                    // 反转字符串
                    char[] charArray = weightStr.ToCharArray();
                    Array.Reverse(charArray);
                    string reversed = new string(charArray);
                    // weightStr = "001.840";
                    // LogHelper.WriteLog($"{DateTime.Now}解析到{serialPort}重量ASCII: {weightStr}, {reversed}");
                    if (double.TryParse(reversed, out double weight))
                    {
                        if (weight > 0)
                        {
                            //临时注释 Console.WriteLine($"{DateTime.Now}解析到{serialPort}重量: {weight} 吨");
                            // 在这里可以触发重量更新事件或处理重量数据
                            // 可选：打印16进制数据用于调试
                            //Console.WriteLine("原始16进制数据: " + BitConverter.ToString(data));
                            //Console.WriteLine("原始16进制转换成ASCII码数据: " + Encoding.ASCII.GetString(data));
                            //StableWeightDetector swd = new StableWeightDetector(3);                          
                            //swd.OutputResult((double)weight);
                            return weight;
                        }
                    }
                }

            }
            else
            {
                //3号磅数据解析 （示例格式：\STX+000060）
                // 检查数据起始符和长度
                if (data.Length >= 8 && data[0] == 0x02) // STX开头
                {
                    // 提取符号和数字部分（跳过STX）
                    string sign = ((char)data[1]).ToString(); // '+'或'-'
                    weightStr = asciiString.Substring(2, 6); // 取6位数字

                    if (double.TryParse(sign + weightStr, out double weight))
                    {
                        if (weight > 0)
                        {
                            //Console.WriteLine("原始16进制数据: " + BitConverter.ToString(data));
                            //Console.WriteLine("原始16进制转换成ASCII码数据: " + asciiString);


                            Console.WriteLine($"{DateTime.Now}解析到{serialPort}重量: {weight / 1000} 吨");
                            LogHelper.WriteLog($"{DateTime.Now}解析到{serialPort}重量: {weight / 1000} 吨");
                            // 在这里可以触发重量更新事件或处理重量数据
                            return Convert.ToDouble(weight / 1000);
                        }
                    }

                }

            }
            //// 可选：打印16进制数据用于调试
            //Console.WriteLine("原始16进制数据: " + BitConverter.ToString(data));
            //Console.WriteLine("原始16进制转换成ASCII码数据: " + Encoding.ASCII.GetString(data));
            return 0;
        }


    }
}
